var GLOBAL_ID = -1;

function getLastPhrase(){

	if (GLOBAL_ID == -1){
	
		var phrases = $("a.phraselink");
			
		var nums = new Array();
		
		// Get all phrases id
		$(phrases).each(function(){
		
			var id = this.id;
			
			nums.push(id);
		
		});
		
		// Get last id to check news
		var last_id = BubbleSortDown(nums,nums.length);
		
		// Get last phrase
		checkNew(last_id);
	}else{
		checkNew(GLOBAL_ID);
	}
	
	

}

// Bubble sort
function BubbleSortDown(arrayName,length) { 

    for (var i=0; i<(length-1); i++) { 
    
        for (var b=i+1; b<length; b++) { 
        
            if (arrayName[b] > arrayName[i]) { 
            
                var temp = arrayName[i]; 
                arrayName[i] = arrayName[b]; 
                arrayName[b] = temp; 
                
    		}  
    		
        } 
        
    }  
    
    return arrayName[0];

}

// Check if server has new phrases
function checkNew(id_p){

	$.getJSON("check_new/"+id_p, function(data, textStatus){
		
		// Ajax returned call
		if (textStatus == "success"){
		
			// Data
			
			if (data == false){
				
				return false;
			}
			else{

				// Make div layers
				var p_container = $("<div id='post"+data.id+"' class='post' style='display: none;'></div>");
				var p_header = $("<h2><a href='/miticas/phrase/"+data.id+"' class='phraselink'>Frase m&iacute;tica n&uacute;mero "+data.id+"</a></h2>");
				var p_phrase = $("<p class='phrase'></p>").html("&quot;"+data.phrase+"&quot;");
				var p_date   = $("<p class='date'>"+data.date+" - <a href='/miticas/phrase/'"+data.id+">"+data.comments+" comentarios</a></p>");
				
				$(p_header).appendTo(p_container);
				$(p_phrase).appendTo(p_container);
				$(p_date).appendTo(p_container);
				
				// Insert new phrase after paragraph rsslink
				$(p_container).insertAfter($("p.rsslink"));
				
				// Fade effect
				$("#post"+data.id).fadeIn(3000);
				
				GLOBAL_ID = data.id;
				
				
			}		
		
		}
			
    });
	

}